package openapi

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"gitlab.ctyun.cn/ctg-dcos/workflow-sdk-go/pkg/client"
)

const (
	INVOKE_WORKFLOW_ENDPOINT = "cf.fc-xinan1.ctyun.cn"
	WORKFLOW_ENDPOINT        = "fc-global.ctapi.ctyun.cn"
)

type CloudFlowClient struct {
	endpoint string
	client   *client.CtapiClient
}

// @Param endpoint ctapi域名
func NewCloudFlowClient(endpoint, ak, sk string, opts ...client.HttpOption) *CloudFlowClient {
	return &CloudFlowClient{
		endpoint: endpoint,
		client:   client.NewCtapiClient(ak, sk, opts...),
	}
}

func (c *CloudFlowClient) SetEndpoint(endpoint string) {
	c.endpoint = endpoint
}

// @Param region 资源池id
// 执行工作流
func (c *CloudFlowClient) InvokeWorkflow(ctx context.Context, region string, req *InvokeFlowRequest) *client.Response {

	header := c.newHeader(region)

	bodys, err := json.Marshal(req)
	if err != nil {
		return &client.Response{
			Error: &client.Error{
				StatusCode: http.StatusBadRequest,
				Msg:        err.Error(),
			},
		}
	}

	url := fmt.Sprint("https://", c.endpoint, "/openapi/v1/execution/start")

	resp, err := c.client.Post(ctx, url, header, bodys)

	if err != nil {
		return &client.Response{
			Error: &client.Error{
				StatusCode: http.StatusInternalServerError,
				Msg:        err.Error(),
			},
		}
	}

	return resp
}

// Query workflow by workflow name prefix
func (c *CloudFlowClient) QueryWorkflow(ctx context.Context, region string, req WorkflowQueryRequest) (
	*OpenAPIResponseMeta[WorkflowQueryResponse], error) {

	header := c.newHeader(region)
	path := GenerateUrl(c.endpoint, "/openapi/v1/workflow/query",
		NewQueryParam("queryPrefix", req.QueryPrefix),
		NewQueryParam("pageNum", fmt.Sprint(req.PageNum)),
		NewQueryParam("pageSize", fmt.Sprint(req.PageSize)),
	)
	res, err := c.client.Get(ctx, path, header)
	if err != nil {
		return nil, err
	}
	if res.Error != nil {
		return nil, res.Error
	}

	var response OpenAPIResponseMeta[WorkflowQueryResponse]
	if err := json.Unmarshal(res.Body, &response); err != nil {
		return nil, err
	}
	return &response, nil
}

func (c *CloudFlowClient) newHeader(region string) http.Header {
	header := http.Header{}
	header.Add("Content-Type", "application/json")
	header.Add("regionId", region)
	return header
}
